package com.jzg.jcptadmin.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.CommonUtil;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.Utils.ScreenUtils;
import com.jzg.jcptadmin.app.ActivityHelp;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.vo.CarDetails;
import com.jzg.jcptadmin.data.vo.CarTypeModel;
import com.jzg.jcptadmin.data.vo.CarTypeSelectModel;
import com.jzg.jcptadmin.data.vo.CarTypeSelectModel.DataBean.ListBeanX.ListBean;
import com.jzg.jcptadmin.data.vo.Make;
import com.jzg.jcptadmin.data.vo.Model;
import com.jzg.jcptadmin.data.vo.Style;
import com.jzg.jcptadmin.presenter.CarConfigParaSelectPresenter;
import com.jzg.jcptadmin.view.CarDiffSelectView;
import com.jzg.jcptadmin.view.CustomRippleButton;
import com.jzg.jcptadmin.viewinterface.ICarDiffInterface;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jzg.jcptadmin.app.AppContext.isNetWork;

/**
 * 备选车型
 * @time 2017/3/20 9:54
 */
public class CarDifferenceConfigSelectActivity extends BaseActivity implements ICarDiffInterface, CarDiffSelectView.OnDiffSelectedItemListener {

    @Bind(R.id.title_content)
    TextView inputTopText;
    @Bind(R.id.tv_right)
    TextView tvRight;
    @Bind(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    @Bind(R.id.crbNext)
    CustomRippleButton crbNext;
    @Bind(R.id.btnNextError)
    Button btnNextError;
    @Bind(R.id.tvCarNumber)
    TextView tvCarNumber;
    @Bind(R.id.tvCarType)
    TextView tvCarType;
    @Bind(R.id.tvCarName)
    TextView tvCarName;
    @Bind(R.id.tvHintError)
    TextView tvHintError;


    @Bind(R.id.car_diff_select)
    CarDiffSelectView carDiffSelectView;
    private CarDetails details;
    private CarConfigParaSelectPresenter carConfigParaSelectPresenter;
    private List<ListBean> datas;//包含所有数据
    private List<ListBean> showDatas;//根据配置项变化的显示数据
    private int REQUEST_CODE = 123;

    private CarTypeModel.DataBean carTypeBean;
    private String productDate;
    private String gear;
    private String drivingMode;
    private String displacement;
    private String vin;
    private String plateType;
    private ListBean selectedType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_diff_config_select);
        ButterKnife.bind(this);
        datas = new ArrayList<>();
        showDatas = new ArrayList<>();
        carConfigParaSelectPresenter = new CarConfigParaSelectPresenter(DataManager.getInstance());
        carConfigParaSelectPresenter.attachView(this);
        inputTopText.setText("备选车型");
        tvRight.setText("参配");

        carDiffSelectView.setOnDiffSelectedItemListener(this);

        details = getIntent().getParcelableExtra("details");
        carTypeBean = (CarTypeModel.DataBean)getIntent().getSerializableExtra("brandSeries");
        productDate = getIntent().getStringExtra("productDate");
        gear = getIntent().getStringExtra("gear");
        drivingMode = getIntent().getStringExtra("drivingMode");
        displacement = getIntent().getStringExtra("displacement");
        vin = getIntent().getStringExtra("vin");
        plateType = getIntent().getStringExtra("plateType");

        tvCarType.setText(carTypeBean.getMakeName()+carTypeBean.getModelName());

        //轮滑图
        ViewGroup.LayoutParams params = convenientBanner.getLayoutParams();
        params.width = RadioGroup.LayoutParams.MATCH_PARENT;
        params.height = ScreenUtils.getScreenWidth(this) * 9 / 16;
        convenientBanner.setLayoutParams(params);
        setPicAdapter();

        ruqestCarList();
    }

    private void setPicAdapter() {
        convenientBanner.setPages(
                new CBViewHolderCreator<NetworkImageHolderView>() {
                    @Override
                    public NetworkImageHolderView createHolder() {
                        return new NetworkImageHolderView();
                    }
                }, details.getCarPicList());

        convenientBanner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {//查看大图
                Intent intent = new Intent(CarDifferenceConfigSelectActivity.this, PhotoForNetActivity.class);
                intent.putExtra("piclists", details);
                intent.putExtra("position", position);
                intent.putExtra("isZonghe", true);
                startActivity(intent);
            }
        });
    }

    class NetworkImageHolderView implements Holder<CarDetails.CarPicListEntity> {
        private ImageView imageView;
        private TextView title;

        @Override
        public View createView(Context context) {
            //你可以通过layout文件来创建，也可以像我一样用代码创建，不一定是Image，任何控件都可以进行翻页
            View view = LayoutInflater.from(context).inflate(R.layout.taskdetail_photo, null);
            imageView = (ImageView) view.findViewById(R.id.photo_img);
            title = (TextView) view.findViewById(R.id.title);
            return view;
        }

        @Override
        public void UpdateUI(Context context, int position, CarDetails.CarPicListEntity data) {
            int tag = position + 1;
            title.setText(data.getItemName18() + "(" + tag + "/" + details.getCarPicList().size() + ")");
            ImageLoader.getInstance().displayImage
                    (data.getPath(), imageView, appContext.options);
        }
    }

    /**
     * 根据变速器的名称得到其对应的ID
     * @author zealjiang
     * @time 2016/11/10 15:13
     */
    private int getGearIdByName(String name){
        if(TextUtils.isEmpty(name)){
            return 0;
        }
        switch (name){
            case "自动" :
                return 1;
            case "手动" :
                return 2;
            case "电动" :
                return 3;
        }
        return 0;
    }

    /**
     * 根据驱动方式的名称得到其对应的ID
     * @author zealjiang
     * @time 2016/11/10 15:13
     */
    private int getDrivingModeIdByName(String name){
        if(TextUtils.isEmpty(name)){
            return 0;
        }
        switch (name){
            case "四驱" :
                return 3;
            case "两驱" :
                return 4;
        }
        return 0;
    }

    /**
     * 根据车系参数请求车辆列表
     */
    private void ruqestCarList(){
        int bsx = getGearIdByName(gear);
        int qdfs = getDrivingModeIdByName(drivingMode);
        carConfigParaSelectPresenter.requestCarDiff(carTypeBean.getModelID()+"",vin,displacement,bsx+"",qdfs+"",productDate,plateType);
    }

    @Override
    public void succeed(CarTypeSelectModel carTypeSelectModel) {
        dismissDialog();
        datas.clear();
        showDatas.clear();
        //重新组装数据
        List<CarTypeSelectModel.DataBean.ListBeanX> listBean = carTypeSelectModel.getData().getList();
        for (int i = 0; i < listBean.size(); i++) {
            CarTypeSelectModel.DataBean.ListBeanX bean = listBean.get(i);
            List<CarTypeSelectModel.DataBean.ListBeanX.ListBean> listDataBeen =  bean.getList();
            if(listDataBeen.size()==0){
                continue;
            }
            for (int j = 0; j < listDataBeen.size(); j++) {
                CarTypeSelectModel.DataBean.ListBeanX.ListBean dataBean = listDataBeen.get(j);
                if(j==0){
                    dataBean.setIsTitle(true);
                    dataBean.setYear(bean.getYear()+"");
                }else{
                    dataBean.setIsTitle(false);
                    dataBean.setYear(bean.getYear()+"");
                }
                datas.add(dataBean);
            }
        }

        showDatas.addAll(datas);
        tvCarNumber.setText("（剩余"+showDatas.size()+"款）");

        CarTypeSelectModel.DataBean.ListBeanX.ListBean dataBean = showDatas.get(0);
        tvCarName.setText(dataBean.getName()+" "+dataBean.getYear()+"款");
        selectedType = dataBean;

        //刷新差异配置项数据
        List<CarTypeSelectModel.DataBean.ConfigListBean> listBeen = carTypeSelectModel.getData().getConfigList();
        carDiffSelectView.initTagFlowData(listBeen);

        if(listBeen.size()==0){
            carDiffSelectView.setVisibility(View.GONE);
            tvHintError.setVisibility(View.VISIBLE);
        }else {
            carDiffSelectView.setVisibility(View.VISIBLE);
            tvHintError.setVisibility(View.GONE);
        }

        if(showDatas.size()==0){
            crbNext.setVisibility(View.GONE);
            btnNextError.setVisibility(View.VISIBLE);
        }else{
            crbNext.setVisibility(View.VISIBLE);
            btnNextError.setVisibility(View.GONE);
        }
    }

    @Override
    public void fail(String string) {
        crbNext.setVisibility(View.GONE);
        btnNextError.setVisibility(View.VISIBLE);
    }


    /**
     * 根据差异项点选配置显示对应列表和对应差异项
     */
    @Override
    public void onDiffSelectedItem(ArrayList<String> selectedItemPos) {
        getCarTypeListByDiff(selectedItemPos);
    }


    /**
     * 根据选中的差异配置来刷新车型列表
     * @author zealjiang
     * @time 2016/11/10 16:54
     */
    public void getCarTypeListByDiff(ArrayList<String> selectedItemPos){
        showDatas.clear();
        //查询出包含差异项的车型
        for (int i = 0; i < datas.size(); i++) {
            String pos = datas.get(i).getPosString();

            String[] poss = pos.split(",");
            //判断此车型是否包含选中的差异配置
            String[] selectedPoss = selectedItemPos.toArray(new String[selectedItemPos.size()]);
            if(CommonUtil.containArray(selectedPoss,poss)){
                showDatas.add(datas.get(i));
            }
        }

        tvCarNumber.setText("（剩余"+showDatas.size()+"款）");
        CarTypeSelectModel.DataBean.ListBeanX.ListBean dataBean = showDatas.get(0);
        tvCarName.setText(dataBean.getName()+" "+dataBean.getYear()+"款");

        selectedType = dataBean;

        //根据筛选出的车型，重新列出差异配置
        carDiffSelectView.resetTagFlow(showDatas);
    }


    /**
     * 获取当前选出的所有款型车型ID
     * @author zealjiang
     * @time 2016/12/7 10:22
     * @return 如果当前选出的备选款型为Null,就返回null
     */
    public ArrayList<String> getShowStyleIdArray(){
        if(showDatas!=null&&showDatas.size()>0){
            ArrayList<String> styleIdArray = new ArrayList<>();
            for (int i = 0; i < showDatas.size(); i++) {
                styleIdArray.add(showDatas.get(i).getStyleId()+"");
            }
            return styleIdArray;
        }else{
            return null;
        }

    }

    @OnClick({R.id.tv_right,R.id.crbNext,R.id.tvCarName})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.tv_right:
                //参配
                if(!isNetWork){
                    MyToast.showShort("对不起，您的网络状况不佳，请确保已经连接网络！");
                    return;
                }
                //获取备选款型styleIds
                ArrayList<String> arrayStyleId = getShowStyleIdArray();
                if(arrayStyleId!=null){
                    Intent intent = new Intent(this, AdmixedContrastActivity.class);
                    intent.putStringArrayListExtra("styleIds",arrayStyleId);
                    startActivity(intent);
                }else{
                    MyToast.showShort("备选款型不可为空");
                }
                break;
            case R.id.crbNext:
                //完成
                if(TextUtils.isEmpty(tvCarName.getText().toString())){
                    MyToast.showShort("选择车辆款型");
                    return;
                }
                Style style = new Style();
                style.setMakeId(carTypeBean.getMakeID());
                style.setModelId(carTypeBean.getModelID());
                style.setFullName(tvCarName.getText().toString());
                style.setId(selectedType.getStyleId());

                Calendar c = Calendar.getInstance();
                int currentYear = c.get(Calendar.YEAR);
                int currentMonth = c.get(Calendar.MONTH) + 1;
                style.setMinYEAR("1990-1");
                style.setMaxYEAR(currentYear+currentMonth+"");

                Make make = new Make();
                make.setIsMakeAll(false);
                make.setMakeId(carTypeBean.getMakeID());
                make.setMakeName(carTypeBean.getMakeName());

                Model model = new Model();
                model.setId(carTypeBean.getModelID());
                model.setName(carTypeBean.getModelName());

                Intent intent = new Intent();
                intent.setAction(Constant.CAR_SELECT_BROADCAST);
                intent.putExtra(Constant.MAKE, make);
                intent.putExtra(Constant.MODEL, model);
                intent.putExtra(Constant.STYLE, (Serializable) style);
                LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
                finish();
                break;
            case R.id.tvCarName:
                if(TextUtils.isEmpty(tvCarName.getText().toString())){
                    return;
                }
                //进入车辆列表
                ActivityHelp.startActivityForResult(this,CarDifferenceActivity.class,"data",(Serializable)showDatas,REQUEST_CODE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REQUEST_CODE) {//品牌、车系选择返回
            if (data!=null){
                ListBean listDataBean = (ListBean) data.getSerializableExtra("ListDataBean");
                tvCarName.setText(listDataBean.getName()+" "+listDataBean.getYear()+"款");
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }
}
